<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="老师" prop="teacherId">
        <el-input
          v-model="queryParams.teacherId"
          placeholder="请输入老师"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="登记时间" prop="logTime">
        <el-date-picker clearable
                        v-model="queryParams.logTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择登记时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['teacher:dailypaper:add']"
        >写日报
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['teacher:dailypaper:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['teacher:dailypaper:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['teacher:dailypaper:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border="1px" v-loading="loading" :data="dailypaperList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="老师" align="center" width="120px" prop="teacher.name"/>
      <el-table-column label="日报时间" align="center" prop="logTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.logTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="创建时间" align="center" prop="creattime" width="180">-->
<!--        <template slot-scope="scope">-->
<!--          <span>{{ parseTime(scope.row.creattime, '{y}-{m}-{d} {h}:{i}') }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="日报内容" align="left" width="720px" prop="content">
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['teacher:dailypaper:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['teacher:dailypaper:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />


    <!-- 添加或修改老师日报对话框 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" width="1100px" append-to-body>
      <el-alert
        title="特别注意"
        type="error"
        show-icon
        description="1.必须要写学生教学跟踪情况  2.差生要加入重点关注   3.日报内容复制一份到教学跟踪表excel表格以及老师沟通群"
        :closable="false"/>
      <br/>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="日报时间" prop="logTime">
          <el-date-picker clearable
                          v-model="form.logTime"
                          type="date"
                          style="width: 200px !important;"
                          value-format="yyyy-MM-dd"
                          :picker-options="pickSelectStart"
                          placeholder="请选择登记时间">
          </el-date-picker>
        </el-form-item>
        <el-divider style="margin: 20px 0 !important;" v-if="!show"></el-divider>
        <!--        教学跟踪-->
        <el-form-item label="教学跟踪" v-for="sp in teachingTracks" v-if="!show">
          <el-select
            style="width: 300px !important;" @change="dialogChangeClass"
            filterable clearable v-model="sp.classId" placeholder="请选择班级">
            <el-option
              v-for="cla in eduadminClasss"
              :key="cla.id"
              :label="cla.name"
              :value="cla.id"
            >
              <span style="float: left">{{ cla.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">
                 <dict-tag :options="dict.type.sys_itsource" :value="cla.school"/>
              </span>
            </el-option>
          </el-select>
          -
          <el-select
            style="width: 200px !important;"
            filterable v-model="sp.studentId" placeholder="请选择学生">
            <el-option
              v-for="student in students"
              :key="student.id"
              :label="student.name"
              :value="student.id"
            >
              <span style="float: left">{{ student.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ student.className }}</span>
            </el-option>

          </el-select>
          -
          <el-select v-model="sp.impartType" placeholder="问题类型" style="width: 150px !important;">
            <el-option
              v-for="dict in dict.type.sys_student_question"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
          -
          <el-date-picker clearable style="width: 190px !important;"
                          v-model="sp.creationtime"
                          type="datetime"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="发生时间">
          </el-date-picker>
          -
          <el-input v-model="sp.discount" placeholder="扣分" style="width: 60px !important;"/>
          <div style="height: 32px;line-height: 32px;">
            <el-input v-model="sp.remark" style="top: -2px;width: 725px;height: 32px;"
                      type="textarea"
                      :rows="1"
                      placeholder="情况描述"/>

            &nbsp;<el-button type="primary" icon="el-icon-plus" style="height: 33px;margin-top: 4px"
                             @click="addline(sp)">加一行
          </el-button>
            &nbsp;<el-button type="danger" icon="el-icon-plus" style="height: 33px;margin-top: 4px"
                             @click="removeline(sp)">减一行
          </el-button>
          </div>
        </el-form-item>
        <el-divider style="margin: 20px 0 !important;"></el-divider>

        <!--        就业跟踪-->
        <el-form-item label="就业跟踪" v-for="sp in studentTracks" v-if="!show">
          <el-select
            style="width: 300px !important;" @change="dialogChangeClass"
            filterable clearable v-model="sp.classId" placeholder="请选择班级">
            <el-option
              v-for="cla in eduadminClasss"
              :key="cla.name"
              :label="cla.name"
              :value="cla.id"
            >
              <span style="float: left">{{ cla.name }}</span>
            </el-option>
          </el-select>
          -
          <el-select
            style="width: 200px !important;"
            @change="changeStudentForJob(sp)"
            filterable v-model="sp.stuName" placeholder="请选择学生">
            <el-option
              v-for="student in students"
              :key="student.id"
              :label="student.name"
              :value="student.name"
            >
              <span style="float: left">{{ student.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ student.className }}</span>
            </el-option>

          </el-select>
          -
          <el-select v-model="sp.afterGoal" placeholder="请选择跟踪目的" style="width: 130px !important;">
            <el-option
              v-for="dict in dict.type.sya_after_goal"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
          -
          <el-date-picker clearable style="width: 150px !important;"
                          v-model="sp.afterTime"
                          type="datetime"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="跟踪时间"
          >
          </el-date-picker>
          -
          <el-select v-model="sp.stuType" placeholder="请选择学生状态" style="width: 120px !important;">
            <el-option
              v-for="dict in dict.type.sys_student_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>

          <div style="height: 32px;line-height: 32px;">
            <el-input v-model="sp.afterNote" style="top: -2px;width: 725px;height: 32px;"
                      type="textarea"
                      :rows="1"
                      placeholder="情况描述"/>

            &nbsp;<el-button type="success" icon="el-icon-plus" style="height: 33px;margin-top: 4px"
                             @click="addJobline(sp)">加一行
          </el-button>
            &nbsp;<el-button type="danger" icon="el-icon-plus" style="height: 33px;margin-top: 4px"
                             @click="removeJobline(sp)">减一行
          </el-button>
          </div>
        </el-form-item>

        <el-divider style="margin: 20px 0 !important;" v-if="!show"></el-divider>
        <el-form-item label="日报内容" prop="content">
          <el-input v-model="form.content"
                    :rows="3"
                    type="textarea"
                    placeholder="对今日工作的总结和明日工作的安排"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="!show" type="success" @click="submitForm">复制并提交日报</el-button>
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import {listDailypaper, getDailypaper, delDailypaper, addDailypaper, updateDailypaper} from "@/api/teacher/dailypaper";
import {listClass} from "@/api/student/class";
import {listStudent} from "@/api/student/student";

export default {
  name: "Dailypaper",
  dicts: ['sys_student_question', 'sya_after_goal', 'sys_student_type', 'sys_itsource'],
  data() {
    return {

      pickSelectStart: {
        disabledDate: (time) => {
          //return time.getTime() < Date.now(); //可选未来天
          //return time.getTime() > Date.now();  // 可选历史天、可选当前天、不可选未来天
          if (time.getTime() > Date.now()) return true;
          // return time.getTime() > Date.now() - 8.64e7;  // 可选历史天、不可选当前天、不可选未来天
          return time.getTime() < Date.now() - 2 * 8.64e7;  // 不可选历史天、可选当前天、可选未来天
          // return time.getTime() < Date.now(); // 不可选历史天、不可选当前天、可选未来天
        },
      },
      pickSelectEnd: {
        disabledDate: (time) => {
          return (
            time.getTime() < new Date(this.Form.start_time).valueOf() - 1 * 24 * 60 * 60 * 1000
          );
        },
      },
      // 班级数据
      eduadminClasss: [],
      // 学生数据
      students: [],
      show: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 日报表格数据
      dailypaperList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        teacherId: null,
        logTime: null,
        creattime: null,
        content: null
      },
      // 表单参数
      // 表单参数
      form: {},
      teachingTracks: [
        {
          classId: null,
          studentId: null,
          impartType: null,
          creationtime: null,
          discount: null,
          remark: null,
          index: "a1ca0f7b-51bd-4bf3-a5d5-6a74f6adc1c7"
        }
      ],
      studentTracks: [
        {
          classIds: null,
          stuName: null,
          afterTime: null,
          afterGoal: null,
          state: null,
          afterNote: null,
          index: "a1ca0f7b-51bd-4bf3-a5d5-6a74f6adc1c7"
        }
      ],
      // 表单校验
      rules: {}
    };
  },
  created() {
    this.getList();
    this.getClasssList();
  },
  methods: {
    getClasssList() {
      listClass().then(res => {
        this.eduadminClasss = res.rows
      })
    },

    getUUID() {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0,
          v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
      });
    },

    changeStudentForJob(row) {
      console.log(row);
      if (row.studentId.length == 1) {
        let studentId = row.studentId[0];
        if (!studentId) return;
        getStudent(studentId).then(response => {
          row.evaluateLevel = response.data.evaluateLevel;
        }).catch(reason => {
        });
      } else {
        row.evaluateLevel = null;
      }
    },

    // 根据班级id查询学生
    getStudentsList(classId) {
      listStudent({pageNum: -1, classId: classId}).then(response => {
        this.students = response.rows;
      }).catch(reason => {
      });
    },

    dialogChangeClass(id) {
      let classId = id;
      this.getStudentsList(classId);
    },
    /** 查询日报列表 */
    getList() {
      this.loading = true;
      listDailypaper(this.queryParams).then(response => {
        this.dailypaperList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        teacherId: null,
        logTime: null,
        content: null,
        teacherName: null,
        name:null,
        teachingTracks: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 减一行 */
    removeJobline(sp) {
      for (let i = 0; i < this.studentTracks.length; i++) {
        if (this.studentTracks[i].index == sp.index) {
          this.studentTracks.splice(i, 1);
          break;
        }
      }
    },
    /**
     * 加一行
     * @param sp
     */
    addJobline(sp) {
      let newObj = JSON.parse(JSON.stringify(sp));
      newObj.studentId = [];
      newObj.evaluate = null;
      newObj.trackTarget = null;
      newObj.evaluateLevel = null;
      newObj.index = this.getUUID();
      this.studentTracks.push(newObj);
    },
    removeline(sp) {
      for (let i = 0; i < this.teachingTracks.length; i++) {
        if (this.teachingTracks[i].index == sp.index) {
          this.teachingTracks.splice(i, 1);
          break;
        }
      }
    },
    addline(sp) {
      //Object.assign({},sp)
      let newObj = JSON.parse(JSON.stringify(sp));
      newObj.studentId = [];
      newObj.impartType = null;
      newObj.dsicount = null;
      newObj.remark = null;
      newObj.index = this.getUUID();
      this.teachingTracks.push(newObj);
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.getClasssList();
      this.show = false;
      this.form.logTime = new Date();
      this.title = "添加老师日报";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getDailypaper(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.show = false;
        this.title = "修改老师日报";
      });
    },
    handleShow(row) {
      this.reset();
      const id = row.id || this.ids
      getDailypaper(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.show = true;
        this.title = "修改老师日报";
      });
    },

    /** 提交按钮 */
    submitForm() {
      // let message = this.copyDayReport();
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id == null) {
            this.form.teachingTracks = this.teachingTracks;
            this.form.studentTracks = this.studentTracks;
            addDailypaper(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              // this.copyTodyTrackInfo();
            });
          } else {
            this.form.teachingTracks = this.teachingTracks;
            this.form.studentTracks = this.studentTracks;
            // this.form.remarks = message;
            updateDailypaper(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },


    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除日报编号为"' + ids + '"的数据项？').then(function () {
        return delDailypaper(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('teacher/dailypaper/export', {
        ...this.queryParams
      }, `dailypaper_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
